/***********************************************************************************
**  
* @copyright (c) 2010-2019, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
************************************************************************************/
/**
* @file	    mjs_server.h
* @version     
* @brief      
* @author   duye
* @date	    2016-12-22
* @note 
*
* 1. 2016-12-22 duye Created this file
*/

#pragma once

#include <map>
#include <duye_system.h>
#include <duye_logger.h>
#include <duye_tcp_server.h>
#include <mjs_client.h>

class MJSClient;

/**
 * @brief service
 */
class MJServer : public duye::TcpServerIf
{
public:
	// <sockfd, MJSClient>
	typedef std::map<int32, MJSClient*> ClientMap;
	typedef std::map<int32, std::string> SockfdAndIpMap;
	
public:
	MJServer();
	~MJServer();

	bool startup();
	bool stop(const bool block = true);

private:
	// implementation duye::TcpServerIf
    virtual bool onNewcon(const duye::IPv4Addr& clientAddr, const int32 clientSockfd);
    virtual bool onDiscon(const int32 clientSockfd);
    virtual bool onRecved(const int32 clientSockfd, const int8* data, const uint64 len);

    bool connectDB();
    void initOnAction();
	bool createServer();
    // 服务进程启动和退出时需要修改数据库中所有mangjingc的连接状态
    bool setClientConnStatusToOffline();

	void addMangjingc(const int32 fd, const std::string& ip);
	void addMangjingw(const int32 fd, const std::string& ip);
	void removeClient(const int32 fd);

	std::string getClientIP(const int32 fd);
	int64 sendToClient(const int32 sockfd, const int8* data, const uint64 len);
	
private:
	friend class MJSClient;
	friend class MJSClientProxy;
	
	duye::TcpServer m_tcp_server;
	ClientMap m_client_map;
	SockfdAndIpMap m_sockfdAndIpMap;
	duye::Mutex m_client_map_mutex;
	MJSOnActionMap m_on_action_map;
	std::string m_web_ip;
};